package com.example.app01

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.app01.model.Card
import com.example.app01.model.CardMatchingGame

class GameActivity : AppCompatActivity() {

    private lateinit var tvUserName: TextView
    private lateinit var tvScore: TextView
    private lateinit var gridLayout: GridLayout
    private lateinit var btnRestart: Button
    private lateinit var btnBack: Button
    private lateinit var tvGameRules: TextView

    private lateinit var game: CardMatchingGame
    private val cardButtons = mutableListOf<Button>()
    private val handler = Handler(Looper.getMainLooper())
    private var isGameActive = true
    private var isProcessing = false

    private var playerName: String = "魏健2023110528"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)

        playerName = intent.getStringExtra("playerName") ?: "魏健2023110528"

        initViews()
        setupGame()
        setupBackPressHandler()
        updateUI()
    }

    private fun initViews() {
        tvUserName = findViewById(R.id.tvUserName)
        tvScore = findViewById(R.id.tvScore)
        gridLayout = findViewById(R.id.gridLayout)
        btnRestart = findViewById(R.id.btnRestart)
        btnBack = findViewById(R.id.btnBack)
        tvGameRules = findViewById(R.id.tvGameRules)

        tvUserName.text = playerName

        btnRestart.setOnClickListener { showRestartConfirmation() }
        btnBack.setOnClickListener { finishWithResult() }

        tvGameRules.text = "游戏规则：\n1. 点击翻开两张牌\n2. 如果匹配：花色相同+4分，数字相同+16分\n3. 如果不匹配：扣2分并翻回背面\n4. 每次翻牌扣1分"
    }

    private fun setupGame() {
        game = CardMatchingGame(16)
        isGameActive = true
        isProcessing = false

        gridLayout.columnCount = 4
        gridLayout.rowCount = 4
        gridLayout.removeAllViews()
        cardButtons.clear()

        // 计算卡片大小
        val screenWidth = resources.displayMetrics.widthPixels
        val availableWidth = screenWidth - 100
        val cardSize = (availableWidth / 4) - 8

        for (i in 0 until 16) {
            val button = createCardButton(i, cardSize)
            cardButtons.add(button)
            gridLayout.addView(button)
        }
    }

    private fun createCardButton(index: Int, size: Int): Button {
        return Button(this).apply {
            text = "?"
            setTextColor(Color.WHITE)
            textSize = 16f
            setTypeface(null, Typeface.BOLD)
            gravity = Gravity.CENTER
            isAllCaps = false

            minWidth = size
            minHeight = (size * 1.4).toInt()

            layoutParams = GridLayout.LayoutParams().apply {
                width = size
                height = (size * 1.4).toInt()
                columnSpec = GridLayout.spec(index % 4)
                rowSpec = GridLayout.spec(index / 4)
                setMargins(2, 2, 2, 2)
            }

            setBackgroundResource(R.drawable.card_background)

            setOnClickListener {
                if (isGameActive && !isProcessing) {
                    onCardClick(index)
                }
            }
        }
    }

    private fun onCardClick(index: Int) {
        if (!isGameActive || game.isGameFinished || isProcessing) return

        val card = game.cardAtIndex(index)
        if (card.isMatched || card.isChosen) return

        isProcessing = true

        // 处理卡片选择
        val result = game.chooseCardAtIndex(index)
        val (isMatch, scoreChange) = result

        updateUI()

        if (isMatch) {
            // 匹配成功，立即更新UI
            handler.postDelayed({
                isProcessing = false
                checkGameFinished()
            }, 500)
        } else if (game.isWaitingForFlip) {
            // 不匹配，需要翻转回去
            handler.postDelayed({
                game.flipBackUnmatchedCards()
                updateUI()
                isProcessing = false
                checkGameFinished()
            }, 1000) // 1秒后翻转回去
        } else {
            // 只选择了一张牌，等待选择第二张
            isProcessing = false
        }
    }

    private fun checkGameFinished() {
        if (game.isGameFinished) {
            isGameActive = false
            handler.postDelayed({
                showGameResult()
            }, 500)
        }
    }

    private fun updateUI() {
        tvScore.text = "当前分数: ${game.score}"

        for (i in cardButtons.indices) {
            val card = game.cardAtIndex(i)
            val button = cardButtons[i]

            updateCardAppearance(button, card)
        }
    }

    private fun updateCardAppearance(button: Button, card: Card) {
        when {
            card.isMatched -> {
                // 已匹配的卡片 - 保持正面显示
                button.setBackgroundResource(R.drawable.card_matched)
                button.text = getCardDisplayText(card)
                button.setTextColor(getSuitColor(card.suit))
                button.isEnabled = false
                button.alpha = 0.7f
            }
            card.isChosen -> {
                // 翻开的卡片 - 显示正面
                button.setBackgroundResource(R.drawable.card_front)
                button.text = getCardDisplayText(card)
                button.setTextColor(getSuitColor(card.suit))
                button.isEnabled = true
                button.alpha = 1.0f
            }
            else -> {
                // 未翻开的卡片 - 显示背面
                button.setBackgroundResource(R.drawable.card_background)
                button.text = "?"
                button.setTextColor(Color.WHITE)
                button.isEnabled = isGameActive && !game.isGameFinished
                button.alpha = 1.0f
            }
        }
    }

    private fun getCardDisplayText(card: Card): String {
        return "${card.suit}${card.rank}"
    }

    private fun getSuitColor(suit: String): Int {
        return when (suit) {
            "♥", "♦" -> Color.RED
            "♠", "♣" -> Color.BLACK
            else -> Color.BLACK
        }
    }

    private fun showGameResult() {
        val message = when {
            game.score >= 30 -> "🎉 太棒了！你是翻牌大师！"
            game.score >= 20 -> "👍 优秀的表现！"
            game.score >= 10 -> "💪 不错！继续加油！"
            game.score >= 0 -> "😊 再接再厉！"
            else -> "🤗 不要气馁，多练习就会进步！"
        }

        AlertDialog.Builder(this)
            .setTitle("游戏结束")
            .setMessage("恭喜完成所有匹配！\n最终得分: ${game.score}\n\n$message")
            .setPositiveButton("再玩一次") { _, _ ->
                restartGame()
            }
            .setNegativeButton("返回主界面") { _, _ ->
                finishWithResult()
            }
            .setCancelable(false)
            .show()
    }

    private fun showRestartConfirmation() {
        if (isGameActive && !game.isGameFinished) {
            AlertDialog.Builder(this)
                .setTitle("重新开始游戏")
                .setMessage("当前游戏进度将会丢失，确定要重新开始吗？")
                .setPositiveButton("确定") { _, _ ->
                    restartGame()
                }
                .setNegativeButton("取消", null)
                .show()
        } else {
            restartGame()
        }
    }

    private fun showExitConfirmation() {
        AlertDialog.Builder(this)
            .setTitle("退出游戏")
            .setMessage("当前游戏进度将会丢失，确定要退出吗？")
            .setPositiveButton("确定") { _, _ ->
                finishWithResult()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun restartGame() {
        game.resetGame()
        setupGame()
        updateUI()
    }

    private fun finishWithResult() {
        val resultIntent = Intent()
        resultIntent.putExtra("score", game.score)
        setResult(Activity.RESULT_OK, resultIntent)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    private fun setupBackPressHandler() {
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (isGameActive && !game.isGameFinished) {
                    showExitConfirmation()
                } else {
                    finishWithResult()
                }
            }
        }
        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }
}